<template>
  <el-card class="form-card">
    <h2>用户登录</h2>
    <el-form :model="form" @submit.prevent="onLogin" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="form.username" required />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" required />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">登录</el-button>
      </el-form-item>
    </el-form>
    <el-alert v-if="msg" type="error" :closable="false" show-icon>{{ msg }}</el-alert>
  </el-card>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { userApi } from '../api/user'

const form = ref({ username: '', password: '' })
const msg = ref('')

const onLogin = async () => {
  try {
    const res = await userApi.login(form.value)
    console.log('登录响应', res)
    if (res && res.userId) {
      localStorage.setItem('user', JSON.stringify(res))
      msg.value = '登录成功！'
      window.location.href = '/'
    } else {
      msg.value = '登录失败，用户信息异常'
    }
  } catch (e) {
    msg.value = '登录失败，请检查用户名或密码'
  }
}
</script>
<style scoped>
.form-card {
  max-width: 400px;
  margin: 40px auto;
}
</style> 